package controllers;


import com.google.gson.JsonObject;
import constants.BuDefault;
import constants.Configurations;
import constants.TplPath;
import constants.api.ApiPass;
import constants.system.MemberShip;
import constants.ws.PageBean;
import duppentity.annotations.Param;
import duppentity.dto.bu.*;
import play.Logger;
import play.Play;
import play.libs.WS;
import utils.JsonUtils;
import utils.RequestHelper;
import utils.Utils;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yangz
 * @desc 服务点相关功能
 */
public class StationController extends ApiController {


    /**
     * 服务点列表
     */
    public static void stationList(){
        String page = TplPath.stationList;
        if (Utils.exitFile(page)){
            renderTemplate(page);
        }
    }

    public static void getStationList() {
        PageBean pageBean = PageBean.get();
        String name = params.get("name", String.class);
        Boolean isIframe = params.get("isIframe", Boolean.class);
        if (isIframe == null) {
            isIframe = false;
        }
        MemberShip memberShip = MemberShip.current();
        JsonObject data = null;
        if(isIframe) {
            data = stationDupp.getStationList(name,null, pageBean.getOffset(), pageBean.pageCount());
        } else {
            data = stationDupp.getStationList(name,memberShip.getId(), pageBean.getOffset(), pageBean.pageCount());
        }
        if (!checkResult(data)) {
            apiError(data);
        }
        List<StationDto> stationDtoList = BuDtoUtil.getStationDtoList(data);
        apiList(data, stationDtoList);
    }


    public static void addStation(){
        String page = TplPath.addStation;
        if (Utils.exitFile(page)){
            renderTemplate(page);
        }
    }


    public static void editStation(){
        String page = TplPath.editStation;
        Long id = params.get("id",Long.class);
        JsonObject result = null;
        if (id>0) {
          result =stationDupp.getStation(id);
        }
        if (result!=null) {
            StationDto station = BuDtoUtil.getStationDto(result);
            if (Utils.exitFile(page)) {
                renderTemplate(page,station);
            }
        }
    }

    public static void readDeviceStatus() {
        String page = TplPath.readDeviceStatus;
        Integer washDeviceStatus = params.get("washDeviceStatus", Integer.class);
        Integer enterGateStatus = params.get("enterGateStatus", Integer.class);
        Integer exitGateStatus = params.get("exitGateStatus", Integer.class);

        if (Utils.exitFile(page)) {
            renderTemplate(page, washDeviceStatus, enterGateStatus, exitGateStatus);
        }

    }

    /**
     * 保存站点
     */
    public static void saveStation(){
        Long id = params.get("id",Long.class);

        String name = params.get("name",String.class);
        Double dPrice = params.get("price",Double.class);
        Integer price = Utils.getIntPrice(dPrice);

        Double dDiscountRate = params.get("discountRate",Double.class);
        Integer discountRate = Utils.getIntPrice(dDiscountRate,10);

        Double lng = params.get("lng",Double.class);
        Double lat = params.get("lat",Double.class);
        String address = params.get("address",String.class);

        String openTimeDesc = params.get("openTimeDesc",String.class);
        Integer openStatus = params.get("openStatus",Integer.class);
        String remark = params.get("remark",String.class);

        String enterRomId = params.get("enterRomId",String.class);
        String exitRomId = params.get("exitRomId",String.class);

        String deviceNo = params.get("deviceNo",String.class);
        MemberShip memberShip = MemberShip.current();
        if (id!=null && id > 0) {
            JsonObject data = stationDupp.editStation(memberShip.getSessionId(),memberShip.getId(),id, name, price,discountRate,lng,lat,address,openTimeDesc,openStatus,remark,enterRomId,exitRomId,deviceNo,MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("result").getAsBoolean()) {
                    apiOk("修改服务站点成功");
                } else {
                    apiError("修改服务站点失败");
                }
            } else {
                apiError(data);
            }
        } else {
            JsonObject data = stationDupp.addStation(memberShip.getSessionId(),memberShip.getId(),name, price,discountRate,lng,lat,address,openTimeDesc,openStatus,remark,enterRomId,exitRomId,deviceNo,MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("id").getAsLong() > 0) {
                    apiOk("保存服务站点成功");
                } else {
                    apiError("保存服务站点失败");
                }
            } else {
                apiError(data);
            }
        }
    }

    /**
     * 异常记录列表
     */
    public static void faultRecordList() {
        Long stationId = params.get("stationId",Long.class);
        String name = params.get("name", String.class);
        String page = TplPath.faultRecordList;
        if (Utils.exitFile(page)) {
            renderTemplate(page, name, stationId);
        }
    }

    public static void getFaultRecordList() {
        Long stationId = params.get("stationId",Long.class);
        Integer deviceType = params.get("deviceType",Integer.class);
        String startCreateTime = params.get("startCreateTime", String.class);
        String endCreateTime = params.get("endCreateTime", String.class);
        String startRestoreTime = params.get("startRestoreTime", String.class);
        String endRestoreTime = params.get("endRestoreTime", String.class);

        PageBean pageBean = PageBean.get();

        JsonObject data = stationDupp.getFaultRecordList(stationId, deviceType, startCreateTime, endCreateTime, startRestoreTime, endRestoreTime, pageBean.getOffset(), pageBean.pageCount());
        if (!checkResult(data)) {
            apiError(data);
        }
        List<StationFaultRecordDto> stationFaultRecordDtoList = FaultUserDtoUtil.getStationFaultRecordDtoList(data);
        apiList(data, stationFaultRecordDtoList);
    }

    /**
     * 异常通知人员列表
     */
    public static void faultUserList() {
        String name = params.get("name", String.class);
        JsonObject data = stationDupp.getStationList(null, null, 0, 10);
        int total = data.get("total").getAsInt();
        String page = TplPath.faultUserList;
        if (Utils.exitFile(page)) {
            renderTemplate(page, name, total);
        }
    }

    public static void getFaultUserList() {
        String name = params.get("name", String.class);
        String mobile = params.get("mobile", String.class);

        PageBean pageBean = PageBean.get();

        JsonObject data = stationDupp.getFaultUserList(name, mobile, pageBean.getOffset(), pageBean.pageCount());
        if (!checkResult(data)) {
            apiError(data);
        }
        List<FaultUserDto> faultUserDtoList = FaultUserDtoUtil.getFaultUserDtoList(data, false);
        apiList(data, faultUserDtoList);
    }

    public static void addFaultUser() {
        String page = TplPath.addFaultUser;
        if (Utils.exitFile(page)) {
            renderTemplate(page);
        }
    }

    public static void editFaultUser() {
        String page = TplPath.editFaultUser;
        Long id = params.get("id", Long.class);
        JsonObject result = null;
        if (id > 0) {
            result = stationDupp.getFaultUser(id);
        }
        if (result != null) {
            FaultUserDto faultUserDto = FaultUserDtoUtil.getFaultUserDto(result, true);
            if (Utils.exitFile(page)) {
                renderTemplate(page, faultUserDto);
            }
        }
    }

    public static void saveFaultUser() {
        String name = params.get("name", String.class);
        String mobile = params.get("mobile", String.class);
        Long id = RequestHelper.getLongParam("id");
        String[] stationIds = params.get("stationId", String.class).split(",");
        List<Long> stationList = new ArrayList<>();
        for(String stationId : stationIds){
            if(!Utils.isNullOrEmpty(stationId)) {
                stationList.add(Long.parseLong(stationId));
            }
        }

        if (id > 0) {
            JsonObject data = stationDupp.updateFaultUser(id, name, mobile, stationList, MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("result").getAsBoolean()) {
                    apiOk("修改异常通知人员成功");
                } else {
                    apiError("修改异常通知人员失败");
                }
            } else {
                apiError(data);
            }
        } else {
            JsonObject data = stationDupp.saveFaultUser(name, mobile, stationList, MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("id").getAsInt() > 0) {
                    apiOk("新增异常通知人员成功");
                } else {
                    apiError("新增异常通知人员失败");
                }
            } else {
                apiError(data);
            }
        }
    }

    public static void deleteFaultUser() {
        Long id = params.get("id", Long.class);

        JsonObject data = stationDupp.deleteFaultUser(id, MemberShip.current().getId());
        if (checkResult(data)) {
            if (data.get("result").getAsBoolean()) {
                apiOk("删除异常通知人员成功");
            } else {
                apiError("删除异常通知人员失败");
            }
        } else {
            apiError(data);
        }
    }

    /**
     * 删除通知人员和站点的关联
     */
    public static void deleteStationFaultUser() {
        String stationFaultUserId = params.get("stationFaultUserId", String.class);

        JsonObject data = stationDupp.deleteStationFaultUser(Long.parseLong(stationFaultUserId), MemberShip.current().getId());
        if (checkResult(data)) {
            if (data.get("result").getAsBoolean()) {
                apiOk("删除关联站点成功");
            } else {
                apiError("删除关联站点失败");
            }
        } else {
            apiError(data);
        }
    }

    public static void selectStation(){
        Boolean isIframe = params.get("isIframe", Boolean.class);
        String page = TplPath.selectStation;
        if (Utils.exitFile(page)){
            renderTemplate(page, isIframe);
        }
    }

    /**
     *  服务点设备复位
     */
    public static void fboxReSet() {
        String id = params.get("id", String.class);

        WS.WSRequest wsRequest = WS.url(Configurations.fboxReSetUrl, id);
        JsonObject resetResult = wsRequest.get().getJson().getAsJsonObject();

        if (checkResult(resetResult)) {
            if (resetResult.get("result").getAsBoolean()) {
                apiOk("设备复位成功");
            } else {
                apiError("设备复位失败");
            }
        } else {
            apiError(resetResult);
        }
    }



    @ApiPass
    public static void  downQr(){
        Long stationId = params.get("id",Long.class);
        JsonObject data = null;
        if (stationId>0) {
            data =stationDupp.getStation(stationId);
        }else{
            apiError("站点编号不存在");
        }
        if (data!=null) {
            StationDto station = BuDtoUtil.getStationDto(data);
            //普通二维码生成地址
            String qrUrl=Configurations.qrUrl;
            //小程序二维码生成地址
            //String qrMinUrl = Configurations.qrMinUrl;

            String qrH5Url = Configurations.qrH5Url;

            //站点地址
            //String minAddress = Configurations.minAddress;
            //总共生成的码数量限制为 100,000，请谨慎调用
            //String result ="?path=".concat(minAddress).concat("&stationId=").concat(stationId.toString()).concat("&size=1024");
            String result =qrUrl.concat(qrH5Url).concat(stationId.toString()).concat("&size=1024");;

            File file = new File("");
            String imageFile=file.getAbsolutePath().concat("/public/downQr/").concat(station.id).concat("_").concat(station.deviceNo).concat(".png");
            //if (!Utils.exitImageFile(imageFile)) {
                //不存在才去请求

                WS.WSRequest wsRequest = WS.url(result);
                InputStream inputStream = wsRequest.get().getStream();
                try {
                    File tmp = Utils.getFile(imageFile);
                    Utils.inputStreamToFile(inputStream, tmp);
                } catch (Exception ex) {
                    Logger.error("downQr:" + ex.getMessage());
                }
            //}

            String page = TplPath.downQr;
            if (Utils.exitFile(page)) {
                renderTemplate(page,station);
            }
        }
    }

}
